package com.hyk.commonLib.common.adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 贺玉琨 on 2019/3/6 0006.
 */

public class FragmentPagerAdapter extends androidx.fragment.app.FragmentPagerAdapter {

    private List<Fragment> mFragments;
    private List<String> tabList;
    private FragmentManager fm;

    public FragmentPagerAdapter(FragmentManager fm) {
        this(fm, new ArrayList<>());
    }

    public FragmentPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.fm = fm;
        mFragments = fragments;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabList.get(position);
    }

    public FragmentPagerAdapter setFragments(List<Fragment> mFragments) {
        this.mFragments = mFragments;
        return this;
    }

    public FragmentPagerAdapter setTabList(List<String> tabList) {
        this.tabList = tabList;
        return this;
    }

    /**
     * 清除缓存fragment
     *
     * @param container ViewPager
     */
    public void clear(ViewPager container) {
        FragmentTransaction mCurTransaction = this.fm.beginTransaction();

        for (int i = 0; i < getCount(); i++) {
            long itemId = this.getItemId(i);
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = this.fm.findFragmentByTag(name);
            if (fragment != null) {//根据对应的ID，找到fragment，删除
                mCurTransaction.remove(fragment);
            }
        }
        mCurTransaction.commitNowAllowingStateLoss();
    }

    /**
     * 等同于FragmentPagerAdapter的makeFragmentName方法，
     * 由于父类的该方法是私有的，所以在此重新定义
     *
     * @param viewId
     * @param id
     * @return
     */
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}